package cc.mycraft;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;

import cc.mycraft.events.MyCraftTimingEvent;

public class EventLoader extends JavaPlugin implements Listener{
	
	public static long startTime;
	public static Set<String> OnlinePlayers;
	
	@Override
	public void onEnable() {
		startTime = new Date().getTime();
		OnlinePlayers = new HashSet<String>();
		getServer().getPluginManager().registerEvents(this, this);
		super.onEnable();
	}

	@Override
	public void onDisable() {
		HandlerList.unregisterAll();
		super.onDisable();
	}
	
	@EventHandler(priority=EventPriority.LOWEST)
	public void onPlayerLogin(PlayerLoginEvent e) {
		if(OnlinePlayers.contains(e.getPlayer().getName().toLowerCase())) {
			e.setResult(Result.KICK_OTHER);
			e.setKickMessage("该玩家已在线");
			return;
		}
		OnlinePlayers.add(e.getPlayer().getName().toLowerCase());
	}
	@EventHandler(priority=EventPriority.LOWEST)
	public void onPlayerQuit(PlayerQuitEvent e) {
		OnlinePlayers.remove(e.getPlayer().getName().toLowerCase());
	}
	@EventHandler(priority=EventPriority.LOWEST)
	public void onPlayerQuit(MyCraftTimingEvent e) {
		Set<String> errs = new HashSet<String>();
		for(String pn:OnlinePlayers) {
			if(Bukkit.getPlayerExact(pn)==null) {
				errs.add(pn);
			}
		}
		for(String pn:errs) {
			OnlinePlayers.remove(pn);
		}
	}
	
}
